package com.sxy.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


import com.sxy.dao.SeckillDao;
import com.sxy.dao.SuccessDao;
import com.sxy.dao.cache.RedisDao;
import com.sxy.dto.Exposer;
import com.sxy.dto.SeckillExecution;
import com.sxy.entity.Seckill;
import com.sxy.entity.Success;
import com.sxy.enums.SeckillStatEnum;
import com.sxy.exception.RepeatKillException;
import com.sxy.exception.SeckillCloseException;
import com.sxy.exception.SeckillException;
import com.sxy.service.SeckillService;

/**  
* @ClassName: SeckillServiceImpl  
* @Description: TODO(实现类)  
* @author xy
* @date 2017年12月8日  
*    
*/ 
@Service
public class SeckillServiceImpl implements SeckillService{
     //日志对象
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	//注入service依赖，spring提供Autowired自动注入，在spring中查找dao类型的实例
	@Autowired
	private SeckillDao seckillDao;
	@Autowired
	private SuccessDao successDao;
	@Autowired
	private RedisDao redisDao;
	//加入一个混淆，不希望用户猜到秒杀URL接口,随意敲打一串md5字符串
	private final String slat="sdjskdhajs125dl*&ask";
	
	@Override
	public List<Seckill> getSeckillList() {
		// TODO Auto-generated method stub
		return seckillDao.queryAll(0, 3);
	}

	@Override
	public Seckill getById(long seckillId) {
		// TODO Auto-generated method stub
		return seckillDao.queryById(seckillId);
	}

	@Override
	public Exposer exportSeckillUrl(long seckillId) {
		// TODO Auto-generated method stub
		//通过Redis缓存降低数据库访问的压力
		//1.访问redis
		Seckill seckill = redisDao.getSeckill(seckillId);
		if(seckill == null){
			//2:访问数据库
		 seckill = seckillDao.queryById(seckillId);
		 if(seckill == null){
				return new Exposer(false, seckillId);			
			}else{
				//3：放入redis
				redisDao.putSeckill(seckill);
			}		 
		}		
		Date startTime = seckill.getStartTime();
		Date endTime = seckill.getEndTime();
	    //拿到系统时间
		Date nowTime = new Date();
		if(nowTime.getTime() < startTime.getTime() 
				|| nowTime.getTime() > endTime.getTime()){			
			return new Exposer(false, seckillId,nowTime.getTime(),
					startTime.getTime(),endTime.getTime());			
		}
		//转化特定字符串的过程，不可逆
		String md5 = getMD5(seckillId);
		return new Exposer(true, md5, seckillId);
	}	
	//生成md5，目的加密秒杀地址
	private String getMD5(long seckillId){
		String base = seckillId+"/"+slat;
		//spring工具生成专门的md5
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
	    return md5;
	}
	
	@Override
	@Transactional	
	public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
			throws SeckillException, RepeatKillException, SeckillCloseException {
		// TODO Auto-generated method stub
		//如果md5等于空或者这个md5不等于接受到的5dm
		if(md5 == null || !md5.equals(getMD5(seckillId))){
			throw new SeckillException("秒杀的数据被重写了！");
		}
		//执行秒杀逻辑：减库存+记录购买行为
		Date nowTime = new Date();
		
		try {
			//记录购买行为
			int insertCount = successDao.inserSuccess(seckillId, userPhone);
			//因为seckillId, userPhone是惟一的，如果重复秒杀则数据冲突。不更新数据库
			if(insertCount <= 0){
				throw new RepeatKillException("重复秒杀！");		
			}else{				
				//减库存,热点商品竞争
				int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
				if(updateCount <= 0 ){
				   //没有更新数据库记录 rollback
					throw new SeckillCloseException("秒杀结束！");
				}else{
					//秒杀成功  commit
					Success success = successDao.queryByIdWithSeckill(seckillId, userPhone);
			        return new SeckillExecution(seckillId,SeckillStatEnum.SUCCESS,success);		
				}								
			}						
		}catch(SeckillCloseException e1){
			//这个异常代表秒杀关闭
			throw e1;
		}catch(RepeatKillException e2){
			//这个异常代表重复秒杀
			throw e2;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			//所有编译期异常，转化为运行期异常
			throw new SeckillException("系统异常"+e.getMessage());
		}		
	}

	@Override
	public SeckillExecution executeSeckillProdure(long seckillId, long userPhone, String md5) {
		// TODO Auto-generated method stub
		if(md5 == null || md5.equals(getMD5(seckillId))){
			return new SeckillExecution(seckillId, SeckillStatEnum.DATA_REWRITE);
		}
		Date killTime = new Date();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("seckillId",seckillId);
		map.put("phone",userPhone);
		map.put("killTime",killTime);
		map.put("result",null);
		//执行存储过程完成后，result会被赋值
		try {
			seckillDao.killByProcedure(map);
			int result = MapUtils.getInteger(map, "result",-2);
		 
			if(result == 1){
				Success s = successDao.
						queryByIdWithSeckill(seckillId, userPhone);
			    return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS,s);
			}else{
				return new SeckillExecution(seckillId, SeckillStatEnum.stateOf(result));				
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
		}
	        return new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR);
	}
}
